
var api          = require('../lib/clientApi');
var exception    = require('../lib/exception');
var config       = require('../config.json'),
    appID        = config.wx.AppID,
    appSecret    = config.wx.AppSecret,
    request      = require('request'),
    util         = require('util'),
    uuid         = require('./uuid'),
    timeutil     = require('./timeutil');

// share
var tokenUrl     = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
var ticketUrl    = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";


// auth
var infoUrl      = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
var accessUrl    = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code';
var detailUrl    = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

var Token        = null,
    Ticket       = null;

var getToken = exports.getToken = function(appID, appSecret, session) {

    return new Promise(function(resolve, reject) {
        if(!session.Token) {
            request(util.format(tokenUrl, appID, appSecret), function(err, res, data) {
                if(err) {
                    reject(err)
                } else {
                    var result = JSON.parse(data);
                    session.Token = result;
                    resolve(result)
                }

            })
        } else {
            resolve(session.Token)
        }
    })
};

var getTicket = exports.getTicket = function(session) {
    return new Promise(function(resolve, reject) {
        if(!session.Ticket) {
            getToken(appID, appSecret, session).then(function(res) {
                request(util.format(ticketUrl, res.access_token), function(err, res, data) {
                    if(err) {
                        reject(err)
                    } else {
                        var result = JSON.parse(data);
                        session.Ticket = result;
                        resolve(result)
                    }
                })
            }).catch(function(err) {
                reject(err)
            })
        } else {
            resolve(session.Ticket)
        }

    })
};

var jsapiSignature = exports.jsapiSignature = function(url) {

    return function(callback) {
        getTicket(this.session).then(function(ticket) {
            var timestamp     = timeutil.getTimeStamp();
            var noncestr      = uuid.generateUUID(16);

            var signatureData          = {};
            signatureData.jsapi_ticket = ticket["ticket"];
            signatureData.noncestr     = noncestr;
            signatureData.timestamp    = timestamp;
            signatureData.url          = url;

            var signatureKeys = [];
            Object.keys(signatureData).forEach(function(key){
                signatureKeys.push(key);
            })
            signatureKeys.sort();

            var signatureStr = "",symbol="";
            signatureKeys.forEach(function(key){
                signatureStr += symbol + key + "=" + signatureData[key];
                symbol="&";
            });

            console.log(signatureStr);
            function sha(message){
                var sha1 = require("crypto").createHash("sha1");
                sha1.update(message);
                return sha1.digest("hex");
            }

            signatureData.signature = sha(signatureStr);
            console.log('sign', sha(signatureStr))
            signatureData.appId = appID;
            callback(null, signatureData);

        }).catch(function(err) {
            callback(err)
        })
    }
}

var getUserInfo = exports.getUserInfo = function(url) {

    var callbackUrl = util.format(infoUrl, appID, url);
    return function *() {
        this.redirect(callbackUrl);
    }
}

var updateUserInfo = exports.updateUserInfo = function *(next) {

    var code;
    var self = this;
    var map = ['', 'm', 'f'];
    try { code = self.query.code; } catch (e) {}

    if(!code) {
        throw exception(exception.ServerError);
    }
    request(util.format(accessUrl, appID ,appSecret, code), function(err, res, data) {

        var result = JSON.parse(data);
        var url = util.format(detailUrl ,result['access_token'], result['openid']);
        console.log('result :', result);
        if(err) {
            throw exception(exception.ServerError);
        }
        request(url, function(err, ress, dataa) {
            if(err) {
                throw exception(exception.ServerError);
            }

            var info = JSON.parse(dataa);
            self.session.Winxin = {};
            console.log('info', info);
            var entity = new api.forWinxinAuth();
            self.session.Winxin['openid']       = entity['openid']        = result['openid'];
            self.session.Winxin['access_token'] = entity['accessToken']   = result['access_token'];
            self.session.Winxin['name']         = entity['name']          = info['nickname'];
            self.session.Winxin['gender']       = entity['gender']        = map[info['sex']];
            self.session.Winxin['province']     = entity['province']      = info['province'];
            self.session.Winxin['country']      = entity['country']       = info['country'];
            self.session.Winxin['avatar']       = entity['avatar']        = info['headimgurl'];
            self.session.Winxin['city']         = entity['city']          = info['city'];

            console.log('begain enter:');
            entity.call(function(err, data){
                console.log('enter ', self.session.wxRefer);
                // koa repeat set header
                if(self.session.wxRefer) {
                    //self.response.res.location = self.session.wxRefer;
                    //self.response.res.end('');
                    return self.redirect(self.session.wxRefer);
                } else {
                    //self.response.res.location ='/';
                    //self.response.res.end('');
                    return self.redirect('/');
                }
            });

        })
    });



}